package Aleehot100;

import java.util.List;

/**
 * ClassName: c022
 * Package: Aleehot100
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/6/11 22:01
 * @Version 1.0
 * @Since 1.0
 */
public class c022 {
    public static void main(String[] args) {

    }


    static class ListNode {
        int val;
        ListNode next;
        public ListNode(int val) {
            this.val = val;
            next = null;
        }
    }

    public ListNode getIntersectionNode(ListNode h1, ListNode h2) {
        if(h1 == null || h2 == null) {
            return null;
        }
        int diff = 0;
        ListNode p1 = h1, p2 = h2;
        // 移动到最后一个节点
        while(p1.next != null) {
            diff++;
            p1 = p1.next;
        }
        while(p2.next != null) {
            diff --;
            p2 = p2.next;
        }
        // 最后一个节点不相等，一定没有相交
        if(p1 != p2) {
            return null;
        }

        // 求相交的节点
        if(diff >= 0) {
            p1 = h1;
            p2 = h2;
        } else {
            p1 = h2;
            p2 = h1;
        }

        diff = Math.abs(diff);
        while(diff > 0) {
            p1 = p1.next;
            diff --;    
        }

        while(p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;
    }
}
